import styles from "./Index.module.css";
import Mynav from "../../components/Mynav/Index";
import { Button, Form, Input, Switch } from "antd-mobile";
import { Dropdown } from "antd-mobile";
import { CalendarPicker, List } from "antd-mobile";
import instance from "../../api/request";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ImageUploader, Space, Toast, Dialog } from "antd-mobile";
import dayjs from "dayjs";

function Index() {
  const navigate = useNavigate();
  // 让下拉可选择：
  // 1) 创建表单实例 form，后面通过 form.setFieldsValue 主动写入被选中的值
  // 2) 使用 depText / disText 存放“就诊科室/主要病症”的当前展示标题
  const [form] = Form.useForm();
  const [depText, setDepText] = useState("请选择就诊科室");
  const [disText, setDisText] = useState("请选择主要病症");
  const [visible2, setVisible2] = useState(false);
  const defaultRange: [Date, Date] = [
    dayjs().toDate(),
    dayjs().add(2, "day").toDate(),
  ];

  //渲染科室
  const [ke, setKe] = useState([]);
  useEffect(() => {
    instance.get("/api/share/knowledgeBase/v1/findDepartment").then((res) => {
      console.log(res);
      setKe(res.data.result);
    });
  }, []);

  //渲染病症
  const [zheng, setZheng] = useState([]);
  const [departmentId] = useState(2);
  useEffect(() => {
    instance
      .get("/api/share/knowledgeBase/v1/findDiseaseCategory", {
        params: {
          departmentId: departmentId,
        },
      })
      .then((res) => {
        console.log(res, "=====病症");
        setZheng(res.data.result);
      });
  }, [departmentId]);

  // 提交：只按接口必需字段发 JSON -> 成功后跳转 /class
  const Onfinsh = (values: any) => {
    const payload = {
      title: values?.title || "",
      departmentId: values?.departmentId || '',
      disease: values?.majorDisease || "",
      detail: values?.detail || "",
      treatmentProcess:values?.treatmentProcess || "",
      amount: 0,
    };
    instance
      .post("/api/user/sickCircle/verify/v1/publishSickCircle", payload, {
        headers: { "Content-Type": "application/json" },
      })
      .then((res) => {
        console.log(res);
        navigate("/class");
      });
  };

  //上传图片
  const [fileList, setFileList] = useState([
    {
      url: "",
    },
  ]);

  function mockUpload(file: File): Promise<ImageUploadItem> {
    throw new Error("Function not implemented.");
  }

  return (
    <div className={styles.bingz}>
      <div className={styles.head}>
        <Mynav />
      </div>

      <div className={styles.nei}>
        <Form
          form={form}
          onFinish={Onfinsh}
          footer={
            <Button block type="submit" color="primary" size="large">
              发表
            </Button>
          }
        >
          <div>
            <Form.Item
              label=""
              name="title"
              rules={[{ required: true, message: "标题不能为空" }]}
            >
              <Input placeholder="请输入标题(最多20个字)" />
            </Form.Item>
          </div>

          <div>
            {/* 仅保留一个隐藏字段：departmentId（后端必须字段） */}
            <Form.Item
              name="departmentId"
              rules={[{ required: true, message: "就诊科室不能为空" }]}
            >
              <Input style={{ display: "none" }} />
            </Form.Item>
            {/* Dropdown 仅做展示与选择，不直接参与表单 */}
            <Dropdown>
              <Dropdown.Item
                key="sorter"
                title={depText} // 本地状态回显当前选择
                style={{ marginRight: "250px" }}
              >
                <div style={{ padding: 12 }} className={styles.ke}>
                  {ke.map(
                    (item,index) => (
                      <div
                        key={index}
                        style={{ marginTop: "20px" }}
                        onClick={() => {
                          // 点击选项：把科室ID写入隐藏字段，用于提交
                          form.setFieldsValue({ departmentId: item.id });
                          // 同时更新标题，实现回显
                          setDepText(item.departmentName);
                        }}
                      >
                        <div>{item.departmentName}</div>
                      </div>
                    )
                  )}
                </div>
              </Dropdown.Item>
            </Dropdown>
          </div>

          <div>
            {/* 同理：隐藏字段做校验与取值 */}
            <Form.Item
              name="majorDisease"
              rules={[{ required: true, message: "主要病症不能为空" }]}
            >
              <Input style={{ display: "none" }} />
            </Form.Item>
            <Dropdown>
              <Dropdown.Item
                key="sorter"
                title={disText}
                style={{ marginRight: "250px" }}
              >
                <div style={{ padding: 12 }} className={styles.ke}>
                  {zheng.map((item, index) => (
                    <div
                      key={index}
                      style={{ marginTop: "20px", cursor: "pointer" }}
                      onClick={() => {
                        //点击选择后，将选择值写入隐藏字段，并更新本地状态
                        form.setFieldsValue({ majorDisease: item.name });
                        //实现回显
                        setDisText(item.name);
                      }}
                    >
                      <div>{item.name}</div>
                    </div>
                  ))}
                </div>
              </Dropdown.Item>
            </Dropdown>
          </div>

          <div>
            {/* 症状详情：Form.Item 内只保留受控组件，提示文字移到外层，防止取值异常 */}
            <Form.Item
              className={styles.zhengx}
              label=""
              name="detail"
              rules={[{ required: true, message: "症状详情不能为空" }]}
            >
              <Input placeholder="请输入症状详情" />
            </Form.Item>
            <div className={styles.zi}>不超过300字</div>
          </div>

          <div style={{ marginTop: "19px" }}>
            <div>请输入最近一段治疗经历</div>
            <div className={styles.fang}>
              <div>
                <Form.Item label="" name="treatmentHospital">
                  <Input placeholder="请输入医院名称" />
                </Form.Item>
              </div>

              <div>
                <Form.Item name="treatmentStartTime">
                  <Dropdown>
                    <Dropdown.Item
                      key="sorter"
                      title="请选择开始时间"
                      style={{ marginRight: "200px" }}
                    >
                      <div style={{ padding: 12 }}>
                        <List.Item
                          onClick={() => {
                            setVisible2(true);
                          }}
                        >
                          选择日期范围
                          <CalendarPicker
                            visible={visible2}
                            defaultValue={defaultRange}
                            selectionMode="range"
                            onClose={() => setVisible2(false)}
                            onMaskClick={() => setVisible2(false)}
                            onChange={(val) => {
                              console.log(val);
                            }}
                          />
                        </List.Item>
                      </div>
                    </Dropdown.Item>
                  </Dropdown>
                </Form.Item>
              </div>

              <div>
                <Form.Item name="treatmentEndTime">
                  <Dropdown>
                    <Dropdown.Item
                      key="sorter"
                      title="请选择结束时间"
                      style={{ marginRight: "190px" }}
                    >
                      <div style={{ padding: 12 }}></div>
                    </Dropdown.Item>
                  </Dropdown>
                </Form.Item>
              </div>

              <div>
                <Form.Item
                  label=""
                  name="treatmentProcess"
                  className={styles.zhengxx}
                >
                  <Input placeholder="请输入治疗过程" />
                </Form.Item>
              </div>
            </div>
          </div>

          <div className={styles.heng}>最多可添加6张图片;长按为图片排序</div>

          <div className={styles.tuadd}>
            <div style={{ marginTop: "29px", marginLeft: "180px" }}>
              <ImageUploader
                value={fileList}
                onChange={setFileList}
                upload={mockUpload}
              />
            </div>
          </div>

          <div className={styles.xuan}>
            <div style={{ fontSize: "14px" }}>提神悬赏额度</div>
            <div style={{ marginLeft: "-20px" }}>
              <Switch />
            </div>
          </div>

          <div className={styles.footer}>
            <div>提升额度可获得更多关注，得到更多建议</div>
          </div>
        </Form>
      </div>
    </div>
  );
}

export default Index;
